package uclick.messenger.client.action.request;

import java.io.File;
import java.io.IOException;
import java.net.Socket;
import java.util.Vector;

import javax.swing.JFileChooser;
import javax.swing.JFrame;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import uclick.messenger.client.action.ProtocolAction;
import uclick.messenger.client.protocol.Protocol;
import uclick.messenger.client.xml.ClientXMLConvertor;

public class RequestFileSendInitAction implements ProtocolAction {
	/**
	 * Logger for this class
	 */
	
	@SuppressWarnings("unchecked")
	@Override
	public void requestExcute(Protocol protocol) {
		ClientXMLConvertor convertor = new ClientXMLConvertor();
		Socket socket = (Socket) protocol.getContent("socket");

		File selectedFile = selectedFile();

		if (selectedFile != null) {
//			<!ELEMENT messenger (protocol,sender,filename,filesize,accept,roomnum,receiverlist)>
			String pc = String.valueOf(protocol.getContent("protocol"));
			String sender = (String) protocol.getContent("sender");
			Vector<String> receiverList = (Vector<String>) protocol.getContent("receiverlist");
			String filename = selectedFile.getPath();
			String filesize = String.valueOf(selectedFile.length());
			String roomnum = (String) protocol.getContent("roomnum"); // Only
			
//			<!ELEMENT messenger (protocol,sender,filename,filesize,accept,roomnum,receiverlist)>			
			Document document = convertor.getDoc();
			Element messengerElement = document.createElement("messenger");
			document.appendChild(messengerElement);
			convertor.createElement(document, messengerElement, "protocol", pc);
			convertor.createElement(document, messengerElement, "sender",sender);
			convertor.createElement(document, messengerElement, "filename",filename);
			convertor.createElement(document, messengerElement, "filesize",filesize);
			convertor.createElement(document, messengerElement, "roomnum",roomnum);
			Element receiverElement = document.createElement("receiverlist");
			messengerElement.appendChild(receiverElement);
			//System.out.println("size : "+receiverList.size());
			if(receiverList!=null){
				for (int i = 0; i < receiverList.size(); i++) {
					convertor.createElement(document, receiverElement, "receiver",receiverList.get(i));
				}
			}
			
			messengerElement.appendChild(receiverElement);

			String reqStr = convertor.textFromXML(document,"xml/file/file_transfer_init.dtd");
			System.out.println("reqStr \n"+reqStr);

			try {
				convertor.writer(reqStr, socket);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

	private File selectedFile() {
		File selectedFile = null;
		JFileChooser chooser = new JFileChooser("");
		int reVal = chooser.showOpenDialog((JFrame) null);
		if (reVal == JFileChooser.APPROVE_OPTION) {
			selectedFile = chooser.getSelectedFile();
		}
		return selectedFile;
	}

}
